<?php

namespace App\Models;

use App\Http\Controllers\Admin\CommonController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
 * 资源banner管理
 */
class ResourceBanner extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_banner';


    /**
     * 获取列表
     * @param limit int 分页大小
     * @param skip_way 跳转方式  1、H5链接，2、应用内部  3 不跳转（默认3）
     * @param is_play    是否发布   1 发布  2 撤销
     * @param keywords string 搜索关键词
     */
    public function lists($search_data = [])
    {
        $keywords = $search_data['keywords'] ?? '';
        $skip_way = $search_data['skip_way'] ?? '';
        $is_play = $search_data['is_play'] ?? '';
        $limit = !empty($search_data['limit']) ? $search_data['limit'] : 10;

        $res = $this->select('id', 'name', 'img', 'link', 'is_play', 'sort', 'create_time', 'skip_way')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('name', 'like', "%$keywords%");
                }
            })->where(function ($query) use ($skip_way, $is_play) {
                if ($skip_way) {
                    $query->where('skip_way', $skip_way);
                }
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
            })->where('is_del', 1)
            ->orderByDesc('sort')
            ->paginate($limit)
            ->toArray();

        return $res;
    }
    /**
     * 详情
     * @param id
     * @param is_play 是否发布
     */
    public function detail($id, $is_play = null)
    {
        $res = $this->select('id', 'name', 'img', 'link', 'is_play', 'sort', 'create_time', 'skip_way')
            ->where('id', $id)->where(function ($query) use ($is_play) {
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
            })->where('is_del', 1)->first();
        if (empty($res)) {
            return false;
        }
        //获取对应数据记录
        if ($res['skip_way'] == 2) {
            $res['type_data'] = $this->getTypeData($res['type'], null,$res['link']);
        }
        return $res;
    }

    /**
     *获取对应数据名称
     * $id
     */
    public function getTypeData($guid)
    {
        $resourceTotalModel = new ResourceTotal();
        return $resourceTotalModel->detail(null,null, $guid);
    }
}
